<template>
  <div class="app-container">
    <!-- 顶部功能 -->
    <div class="filter-container" style="margin-bottom: 15px">
      <!-- 题库名 -->
      <el-input
        v-model="queryParams.name"
        placeholder="题库名"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <!-- 一些按钮 -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleShowAll"
      >
        显示全部
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加题库
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="danger"
        icon="el-icon-delete"
        @click="handleDelete"
      >
        批量删除
      </el-button>
      <!-- 切换按钮 -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-refresh"
        @click="toggleRecycleBin"
      >
        {{ recycleBinMode ? '显示正常数据' : '显示回收站' }}
      </el-button>

    </div>

    <!--弹出框-->
    <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="30%">
      <!--普通表单-->
      <!-- name\open\remark -->
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题库名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="是否开放" prop="open">
          <el-radio v-model="form.open" :label="0">否</el-radio>
          <el-radio v-model="form.open" :label="1">是</el-radio>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" />
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 抽屉 -->
    <el-drawer
      title="章节管理"
      :visible.sync="drawerVisable"
      size="50%"
      :wrapper-closable="false"
      :destroy-on-close="true"
    >
      <chapter v-if="drawerVisable" :bank-id="bankId" @close-event="drawerVisable = false" />
    </el-drawer>

    <!--数据表格-->
    <el-table v-loading="loading" :data="bankList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="题库名" align="center" prop="name" />
      <el-table-column label="单选题数量" align="center" prop="radioNum" />
      <el-table-column label="多选题数量" align="center" prop="checkNum" />
      <el-table-column label="判断题数量" align="center" prop="judgmentNum" />
      <el-table-column label="填空题数量" align="center" prop="blankNum" />
      <el-table-column label="简答题数量" align="center" prop="shortAnswerNum" />
      <el-table-column label="是否开放" align="center" prop="open">
      <template slot-scope="scope">
        <el-tag :type="scope.row.open === 1 ? 'success' : 'danger'">
          {{ scope.row.open === 1 ? '开放' : '停用' }}
        </el-tag>
      </template>
      </el-table-column>
      <el-table-column label="逻辑删除" align="center" prop="deleteStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deleteStatus === 1 ? 'success' : 'danger'">
            {{ scope.row.deleteStatus === 1 ? '正常' : '已删除' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column fixed="right" label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="small"
            @click="handleChapter(scope.row)"
          >章节管理</el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="success"
            size="small"
            v-if="scope.row.deleteStatus === 2"
            @click="handleDelete(scope.row)"
          >
            恢复
          </el-button>
          <el-button
            type="danger"
            size="small"
            v-if="scope.row.deleteStatus === 1"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import {
  // getRepoCount,
  // // queryRepos,
  // queryReposByPage,
  // addRepo,
  // deleteRepo,
  // deleteRepos,
  // updateRepo
  addBank,
  updateBank,
  listBank,
  getBank,
  delBank, delBankByIds
} from '@/api/teacher/bank'
import chapter from './chapter.vue'

export default {
  name: 'Bank',
  components: { chapter },
  directives: { waves },
  data() {
    return {
      total:0,
      recycleBinMode: false,
      // 表格数据
      tableData: [],
      // 记录总数
      recordTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        radioNum: null,
        checkNum: null,
        judgmentNum: null,
        blankNum: null,
        shortAnswerNum: null,
        open: null,
        deleteStatus: 1,
      },
      // 题库表格数据
      bankList: [],
      // 对话框表单显示
      dialogFormVisible: false,
      // 抽屉框显示
      drawerVisable: false,
      // 表单类型（添加数据:0,修改数据:1）
      formType: 0,
      // 表单数据
      form: {
        id: null,
        name: null,
        open: null,
        remark: null
      },
      rules: {
        name: [{ required: true, message: '请输入题库名', trigger: 'blur' }]
      },
      // 题库id
      bankId: null
    }
  },
  computed: {
    // 通过表单类型计算表单标题
    formTitle() {
      return this.formType === 0 ? '添加记录' : '修改记录'
    }
  },
  // 创建后
  created() {
    // console.log(111)
    // 从服务器获取数据表格第一页的信息
    // 默认page=1，size=10
    this.getList()
  },
  methods: {
    // 查询分页
    getList() {
      this.loading = true;
      listBank(this.queryParams).then(response => {
        this.bankList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
// 切换显示模式
    toggleRecycleBin() {
      this.recycleBinMode = !this.recycleBinMode;
      console.log('Recycle Bin Mode:', this.recycleBinMode); // 输出状态查看是否正常
      this.queryParams.deleteStatus = this.recycleBinMode ? 2 : 1; // 确保状态切换正确
      this.queryParams.pageNum = 1; // 重置到第一页
      this.getList(); // 数据重新加载
    },


    // 分页大小改变监听
    handleSizeChange(curSize) {
      this.queryParams.limit = curSize
      this.getList()
    },

    // 点击分页监听方法
    handleCurrentChange(curPage) {
      this.queryParams.page = curPage
      this.getList()
    },

    // 搜索
    handleFilter() {
      this.queryParams.page = 1
      this.getList()
    },

    handleShowAll() {
      this.queryParams.page = 1;  // 重置页码为第一页
      this.queryParams.name = null;  // 清空题库名
      this.queryParams.radioNum = null;  // 清空单选题数量
      this.queryParams.checkNum = null;  // 清空多选题数量
      this.queryParams.judgmentNum = null;  // 清空判断题数量
      this.queryParams.blankNum = null;  // 清空填空题数量
      this.queryParams.shortAnswerNum = null;  // 清空简答题数量
      this.queryParams.open = null;  // 清空是否开放
      this.queryParams.deleteStatus = null;  // 恢复为正常数据（不是回收站）

      this.getList();  // 重新加载数据
    },


    // 点击添加记录
    handleCreate() {
      // 表单是添加状态
      this.formType = 0
      // 将空数据置入form
      this.form = {
        id: null,
        name: null,
        open: 0,
        remark: null
      }
      // 显示表单框
      this.dialogFormVisible = true
    },

    // 点击修改记录
    handleUpdate(row) {
      // 表单是修改状态
      this.formType = 1
      // 将行数据置入form
      this.form = {
        id: row.id,
        name: row.name,
        open: Number(row.open),
        remark: row.remark
      }
      // 显示表单框
      this.dialogFormVisible = true
    },

    // 添加和更新的提交表单
    submitForm() {
      if (this.formType === 0) {
        // 添加记录
        addBank(this.form).then((res) => {
          if (res.code === 200) {
            this.$message.success('添加记录成功')
            // 跳转到末尾
            getBank().then((res) => {
              this.recordTotal = res.data
              this.queryParams.page = Math.ceil(
                this.recordTotal / this.queryParams.limit
              )
              this.handleCurrentChange(this.queryParams.page)
            })
          } else {
            this.$message.error('添加记录失败')
          }
          this.dialogFormVisible = false // 关闭对话框
        })
      } else if (this.formType === 1) {
        // 更新记录
        updateBank(this.form).then((res) => {
          if (res.code === 200) {
            this.$message.success('更新记录成功')
            this.getList()
          } else {
            this.$message.error('更新记录失败')
          }
          this.dialogFormVisible = false // 关闭对话框
        })
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;

      // 判断 delete_status 是否为 2，如果是，则执行修改操作
      if (row.deleteStatus === 2) {
        this.$modal.confirm('题库编号为"' + ids + '"的数据项状态为已删除，是否确认恢复？').then(function() {
          // 执行修改操作，将 delete_status 改为 1
          const data = {
            id: ids,  // 传入题库ID
            deleteStatus: 1 // 设置 delete_status 为 1（恢复）
          };
          return updateBank(data); // 调用更新方法
        }).then(() => {
          this.getList(); // 重新获取数据
          this.$modal.msgSuccess("恢复成功");
        }).catch(() => {});
      } else {
        // 否则执行删除操作
        this.$modal.confirm('是否确认删除题库编号为"' + ids + '"的数据项？').then(function() {
          return delBank(ids); // 执行删除操作
        }).then(() => {
          this.getList(); // 重新获取数据
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },



    // 点击章节管理
    handleChapter(row) {
      this.bankId = row.id
      this.drawerVisable = true
    }
  }
}
</script>

<style scoped>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
::v-deep .el-drawer__body {
  overflow: auto;
}
/*2.隐藏滚动条，太丑了*/
/* ::v-deep .el-drawer__container ::-webkit-scrollbar{
    display: none;
} */
</style>
